#include <stdio.h>
#include <string.h>
#include <stdlib.h>
#include <arpa/inet.h>
#include <sys/socket.h>

void error (char *s);

struct temp
{
	int i;
};

int main (void) {
	int recv_data;
	FILE *fp;
	struct sockaddr_in server, client;
	struct temp t;		// received data
	int socketID=socket(AF_INET, SOCK_DGRAM, 0);	//socket initialization
	if(socketID==-1){	
		error("socket");
	}
	
	memset ((char*) &server, 0, sizeof(server));
	server.sin_family = AF_INET;
	server.sin_port = htons (4385);		// server port
	server.sin_addr.s_addr = htonl(INADDR_ANY);

	if( bind(socketID, (struct sockaddr*)&server, sizeof(server))==-1){	// socket binding
		error("bind");
	}

	while(1){
		printf("Waiting for data..\n");
		fflush(stdout);
		int size = sizeof(client);
		recv_data = recvfrom(socketID, (void*)&t, sizeof(t), 0, (struct sockaddr*)&client, &size);
		if(recv_data==-1){
			error("recvfrom()");
		}

		printf("New temp: %d\n", t.i);
		fflush(stdout);

		fp = fopen("temp_data.txt", "a");
		fprintf(fp, "insert into Temp (temp) values (%d);\n", t.i);
		fclose(fp);

	}

	close(socketID);
	return 0;
}
void error (char *s){
	perror (s);
	exit(1);
}


